import type { Plugin } from "vite";
import fs from "node:fs";
import * as electronBuilder from "electron-builder";
import path from "path";
const buildBackground = () => {
  require("esbuild").buildSync({
    entryPoints: ["src/background.ts"],
    bundle: true,
    outfile: "dist/background.js",
    platform: "node",
    target: "node12",
    external: ["electron"],
  });
};
export const ElectronBuildPlugin = (): Plugin => {
  return {
    name: "electron-build",
    closeBundle() {
      buildBackground();
      const json = JSON.parse(fs.readFileSync("package.json", "utf-8"));
      json.main = "background.js";
      fs.writeFileSync("dist/package.json", JSON.stringify(json, null, 4));
      fs.mkdirSync("dist/node_modules");
      electronBuilder.build({
        config: {
          directories: {
            output: path.resolve(process.cwd(), "release"),
            app: path.resolve(process.cwd(), "dist"),
          },
          asar: true,
          appId: "com.example.app",
          productName: "vite-electron",
          nsis: {
            oneClick: false,
            allowToChangeInstallationDirectory: true,//充许用户选择安装目录
          },
        },
      });
    },
  };
};
